package com.hjx.springbootserver.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.util.Enumeration;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DownloadController {
	@Autowired
	HttpServletRequest request;
	
	@RequestMapping("/download")
	public void login(HttpServletResponse res){
		File file = new File("D:\\迅雷下载\\勇敢Z游戏：决Z丛林.1080p.BD中英双字[最新电影www.6vhao.tv].mp4");
		System.out.println(file.length()+"=="+file.exists());
		Enumeration<String> headerNames = request.getHeaderNames();
		while(headerNames.hasMoreElements()){
			String nextElement = headerNames.nextElement();
			System.out.println(nextElement+"=="+request.getHeader(nextElement));
		}
		long start=0;
		long end=file.length()-1;
		String range = request.getHeader("range");
		if(range!=null){
			String[] split = range.split("=");
			if (split!=null&&split.length==2) {
				String[] split2 = split[1].split("-");
				if (split2!=null) {
					start=Long.valueOf(split2[0]);
					if (split2.length==2) {
						try {
							end=Long.valueOf(split2[0]);
						} catch (NumberFormatException e) {
							
						}
					}
				}
			}
		}
		System.out.println("下载数据："+start+"-"+end);
		res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");  
        res.setHeader("Content-Disposition", "attachment;filename="+processFileName(request, file.getName()));
        res.setContentLengthLong(file.length());
        BufferedInputStream bis = null;
        ServletOutputStream os = null;
        long downloadLendth=end-start+1;
        long length=0;
        try(RandomAccessFile raf=new RandomAccessFile(file, "r")) {
        	raf.seek(start);
        	os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(file));
			byte[] b = new byte[1024];
			int readSize=b.length;
			if (downloadLendth-length<readSize) {
				readSize=(int) (downloadLendth-length);
			}
			int read=0;
			while ((read=raf.read(b,0,readSize)) != -1&&length<downloadLendth) {
				length+=read;
				os.write(b,0,read);
				os.flush();
			} 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println(length);
			try {
				bis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println(request.getParameterMap());
	}
	
	/** 
     *  处理导出生成的Excel文件名在火狐或ie下出现乱码的问题
     * @Title: processFileName 
     *  
     * @Description: ie,chrom,firfox下处理文件名显示乱码 
     */  
    public static String processFileName(HttpServletRequest request, String fileNames) {  
        String codedfilename = null;  
        try {  
            String agent = request.getHeader("USER-AGENT");  
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent  
                    && -1 != agent.indexOf("Trident")) {// ie  
  
                String name = java.net.URLEncoder.encode(fileNames, "UTF8");  
  
                codedfilename = name;  
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等  
  
  
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return codedfilename;  
    }
}
